//
//  MAMapViewController.m
//  YunGui
//
//  Created by HanenDev on 16/4/7.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "MAMapViewController.h"
#import "SQButton.h"

@interface MAMapViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    UIView         *_searchView;
    UITextField    *_searchTF;
    UISearchBar    *_searchBar;
    
    //点击标注出现的视图
    UIView         *_locationView;
    UILabel        *_nameLabel;
    UILabel        *_addressLabel;
    UIImageView    *_locImage;
    
    NSMutableArray *_placeArray;
    NSString       *userClickPlace;
    
    UITableView    *_tableview;
    UIView         *viback;
    
    NSString       *lastSearchString;
    
    CLLocationCoordinate2D  userNowCoordinate;
    CLLocationCoordinate2D  clickCoordinate;
    CLLocationCoordinate2D  searchCoordinate;
    
    BOOL         isJump;
    int   currentPage;
}
@property(nonatomic,strong)NSString *provinceStr;
@property(nonatomic,strong)NSString * cityStr;//定位之后的城市
@property(nonatomic,strong)NSString *districtStr;//搜索之后的小区名称

@end

@implementation MAMapViewController
@synthesize revealController;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"小区地图";
    self.navigationItem.leftBarButtonItem=[ViewTool getListBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];
    
    isJump = YES;
    
    SQButton *btn = [[SQButton alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:20], [UIView getWidth:20])];
    [btn setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    btn.isSelected = NO;
    [btn addTarget:self action:@selector(clickToGetSearch:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem=item;

    [self initMapView];
    
    [self createUI];
    
    currentPage = 1;
    
}
- (void)initMapView{
    _mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _mapView.delegate = self;
    _mapView.showsCompass= NO;//关闭指南针
    _mapView.showsScale= NO;//关闭比例尺
    _mapView.mapType = MAMapTypeStandard;
    [self.view addSubview:_mapView];
    
    _locationManager = [[AMapLocationManager alloc] init];
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
    
    _mapView.showsUserLocation=YES;//开启定位
    _mapView.userTrackingMode = MAUserTrackingModeNone;
    [_mapView setZoomLevel:16.1 animated:YES];
    
    //初始化检索对象
    _searchApi = [[AMapSearchAPI alloc] init];
    _searchApi.delegate = self;
    
    
}
- (void)initDataWithSearch:(NSString *)str withPage:(int)pageNum{
    [SVProgressHUD show];
    if (self.provinceStr != nil) {
        NSMutableDictionary * dic;
        
        if (self.cityStr.length == 0) {
            dic = [[NSMutableDictionary alloc]initWithDictionary:@{@"method":@"app.village.map",@"city":self.provinceStr,@"province":self.provinceStr,@"page":@(pageNum),@"pageNum":@(10)}];
        }else{
            dic = [[NSMutableDictionary alloc]initWithDictionary:@{@"method":@"app.village.map",@"city":self.cityStr,@"province":self.provinceStr,@"page":@(pageNum),@"pageNum":@(10)}];
        }
        if (_searchBar.text.length != 0) {
            [dic setObject:str forKey:@"search"];
        }
        [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dic] success:^(id data) {
            [SVProgressHUD dismiss];
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",jsonDic);
            
            if ([jsonDic[@"status"] isEqualToString:@"SUCCESS"]) {
                
                NSArray *dataArray = jsonDic[@"data"][@"listData"];
                NSMutableArray *annotations = [NSMutableArray array];
                
                for (int i = 0; i<dataArray.count; i++) {
                    NSDictionary *dataDic = dataArray[i];
                    
                    CGFloat latitude = [dataDic[@"latitude"] floatValue];
                    CGFloat longitude = [dataDic[@"longitude"] floatValue];
                    
                    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){latitude,longitude};
                    
                    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
                    annotation.coordinate = pt;
                    annotation.subtitle = dataDic[@"address"];
                    annotation.title = dataDic[@"title"];
                    [annotations addObject:annotation];
                    [_placeArray addObject:annotation];
                }
                
                [_mapView addAnnotations:annotations];
                [_mapView showAnnotations:annotations animated:YES];
                
                [_tableview reloadData];
                [_tableview.mj_footer endRefreshing];
                
                if ([jsonDic[@"data"][@"total"] integerValue] == _placeArray.count) {
                    [_tableview.mj_footer endRefreshingWithNoMoreData];
                }else{
                [_tableview.mj_footer endRefreshing];
                }
            }else{
                [Tools showMessage:jsonDic[@"msg"] view:self];
                [_tableview.mj_footer endRefreshing];
        }
        } fail:^(NSError *error) {
            [SVProgressHUD dismiss];
            [Tools showMessage:error.localizedDescription view:self];
            NSLog(@"%@",error);
        }];
    }
    
}
- (void)creatTableView{
    viback = [[UIView alloc] initWithFrame:CGRectMake(0, _searchView.height, kScreenWidth, kScreenHeight - _searchView.height)];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackView)];
    [viback addGestureRecognizer:tap];
    
    [self.view addSubview:viback];
    viback.alpha = 0;
    viback.backgroundColor = GRAYCOLOR;
    
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, _searchView.height, kScreenWidth, kScreenHeight - _searchView.height -64 )];
    _tableview.backgroundColor = [UIColor colorWithRed:241.0f/255.0f green:241.0f/255.0f blue:241.0f/255.0f alpha:1];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    _tableview.tableFooterView = [[UIView alloc]init];
    _tableview.alpha = 0;
    _tableview.hidden = YES;
    
    // 上拉刷新
    _tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            currentPage++;
            if (_searchBar.text.length != 0) {
                
                [self initDataWithSearch:_searchBar.text withPage:currentPage];
            }else{
                
                [self initDataWithSearch:@"" withPage:currentPage];
                
            }
        });
    }];

}
- (void)tapBackView{
    viback.alpha = 0;
}
#pragma mark
#pragma mark  ------tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _placeArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *mapCell = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mapCell];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mapCell];
    }
    
    MAPointAnnotation *point = _placeArray[indexPath.row];
    
    cell.textLabel.text = point.title;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *arr = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:arr];
    
    MAPointAnnotation *point = _placeArray[indexPath.row];
    userClickPlace = point.title;
    searchCoordinate = point.coordinate;
        
    [_mapView addAnnotation:point];
    NSLog(@"%f  +++++ %f",point.coordinate.latitude,point.coordinate.longitude);
    
    [_mapView setCenterCoordinate:point.coordinate];
    _mapView.zoomLevel = 17.1f;
    [UIView animateWithDuration:0.25 animations:^{
        _tableview.alpha = 0;
        
    } completion:^(BOOL finished) {
        _tableview.hidden = YES;
        viback.alpha = 0;
        viback.hidden = YES;
    }];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_searchBar resignFirstResponder];
    
}
- (void)poiToDeGeoCodeWith:(CLLocationCoordinate2D )coordinate
{
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0,0};
    pt = coordinate;
    NSLog(@"===%f,  %f",coordinate.latitude,coordinate.longitude);
    AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
    regeoRequest.location = [AMapGeoPoint locationWithLatitude:pt.latitude     longitude:pt.longitude];
    regeoRequest.requireExtension = NO;
    
    //发起逆地理编码
    [_searchApi AMapReGoecodeSearch:regeoRequest];
    clickCoordinate =  pt;
}

-(void)createUI{
    CGFloat searchH = 60;
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, searchH)];
    [_searchView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Btn_Normal_Sousuodi.png"]]];
    _searchView.hidden = YES;

    [self.view addSubview:_searchView];
    
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(20, 10, kScreenWidth-40, searchH - 2*10)];
    [_searchBar setBackgroundImage:[ViewTool getImageFromColor:[UIColor whiteColor] WithRect:CGRectMake(0, 0, kScreenWidth, searchH)]];
//    _searchBar.backgroundColor = [UIColor redColor];
    _searchBar.userInteractionEnabled = YES;
    _searchBar.placeholder =@"小区名称";
    _searchBar.layer.cornerRadius  = 4;
    _searchBar.layer.masksToBounds = YES;
    UITextField *tf = [_searchBar valueForKey:@"_searchField"];
    [tf setValue:LEFTLINECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [tf setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];

    _searchBar.delegate = self;
    [_searchView addSubview:_searchBar];
    
    
    //下面弹出来的视图
    [self initViews];
    
}
- (void)initViews{
    CGFloat startX = [UIView getWidth:20];
    _locationView = [[UIView alloc]initWithFrame:CGRectMake(startX, kScreenHeight - 70-70 - [UIView getHeight:20], kScreenWidth - 2*startX, 70)];
    _locationView.hidden = YES;
    _locationView.backgroundColor = [UIColor whiteColor];
    
    
    _locImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 70, 70)];
    _locImage.image = [UIImage imageNamed:@""];
    _locImage.backgroundColor = BlueColor;
    [_locationView addSubview:_locImage];
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(_locImage.maxX + 10, 10, _locationView.width - _locImage.maxX - 50, 30)];
    _nameLabel.textColor = [UIColor orangeColor];
    _nameLabel.font = [UIFont systemFontOfSize:18.0f];
    [_locationView addSubview:_nameLabel];
    
    _addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(_locImage.maxX + 10, _nameLabel.maxY, _locationView.width - _locImage.maxX - 50, 20)];
    _addressLabel.textColor = [UIColor grayColor];
    _addressLabel.font = [UIFont systemFontOfSize:16.0f];
    [_locationView addSubview:_addressLabel];
    
    UIButton *locBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - startX - 18 -35, (70-18)/2, 18, 18)];
    [locBtn setImage:[UIImage imageNamed:@"Btn_Normal_Sanjiao"] forState:UIControlStateNormal];
    
       [locBtn addTarget:self action:@selector(clickGoToDetail:) forControlEvents:UIControlEventTouchUpInside];
    
    [_locationView addSubview:locBtn];
    
    _placeArray = [NSMutableArray array];
    
    [self creatTableView];
}
- (void)addAnnotionWith:(CLLocationCoordinate2D )coordinate withTitle:(NSString *)title withSubtitle:(NSString * )subtitle
{
    
    NSArray *array = _mapView.annotations;
    [_mapView removeAnnotations:array];
    if (_locationView.hidden == NO) {
        _locationView.hidden = YES;
    }
    
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    annotation.subtitle = subtitle;
    annotation.title = title;
    [_mapView addAnnotation:annotation];
    
}
#pragma mark  ------跳转
- (void)clickGoToDetail:(UIButton *)btn{
    MAMapDetailViewController *vc= [[MAMapDetailViewController alloc]init];
    vc.cityStr = self.cityStr;
    vc.districtStr = userClickPlace;
    vc.myLocation = userNowCoordinate;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark
#pragma mark  ------地图相关的代理
//定位api
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{
    
    [_locationManager stopUpdatingLocation];

    _mapView.centerCoordinate = location.coordinate;
    userNowCoordinate = location.coordinate;
    
    //    _mapView.showsUserLocation = NO;//定位成功之后关闭定位
    
    
    //构造AMapReGeocodeSearchRequest对象
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:userNowCoordinate.latitude     longitude:userNowCoordinate.longitude];
    regeo.requireExtension = NO;
    //发起逆地理编码
    [_searchApi AMapReGoecodeSearch: regeo];

}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView*annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil){
            
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
//            ((MAPinAnnotationView*)annotationView).animatesDrop = YES;//设置标注动画显示，默认为NO
        }
        annotationView.canShowCallout= YES;//设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;   //设置标注可以拖动，默认为NO
        annotationView.image = [UIImage imageNamed:@"Btn_Normal_Weizhi2"];
        
        
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        return annotationView;
    }
    
    return nil;
}

//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    //对于直辖市，response.regeocode.addressComponent对象的city属性值为空，province属性中是直辖市名称。
    NSString *province = response.regeocode.addressComponent.province;
    NSString *city = response.regeocode.addressComponent.city;
    
    if (province != nil) {
        if ([province rangeOfString:@"省"].location != NSNotFound) {
            self.provinceStr = [province componentsSeparatedByString:@"省"][0];
        }else if ([province rangeOfString:@"市"].location != NSNotFound) {
            self.provinceStr = [province componentsSeparatedByString:@"市"][0];
        }else{
            self.provinceStr = province;
        }
    }
    
    if (city != nil) {
        if ([city rangeOfString:@"市"].location != NSNotFound) {
            self.cityStr = [city componentsSeparatedByString:@"市"][0];
        }else{
            self.cityStr = city;
        }
    }else{
        self.cityStr = [DataTool changeType:city];
    }
    
    [self initDataWithSearch:@"" withPage:currentPage];
    
    NSLog(@"%@++++++%@",self.cityStr,self.provinceStr);
     NSString *addrDetailStr = [NSString stringWithFormat:@"%@%@%@",response.regeocode.addressComponent.district,response.regeocode.addressComponent.streetNumber.street,response.regeocode.addressComponent.streetNumber.number];
    
    
    NSString * place = [NSString stringWithFormat:@"%@%@",self.cityStr,addrDetailStr];
    
    if (userClickPlace != nil) {
        [self addAnnotionWith:clickCoordinate withTitle:userClickPlace withSubtitle:place];
    }
    
}
//POI查询回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    // 清除屏幕中所有的annotation
    [_mapView removeAnnotations:_mapView.annotations];
    if (_locationView.hidden == NO) {
        _locationView.hidden = YES;
    }
    
    NSMutableArray *annotations = [NSMutableArray array];
    for (int i = 0; i < response.pois.count; i++) {
        AMapPOI* poi = [response.pois objectAtIndex:i];
        MAPointAnnotation *maaa = [[MAPointAnnotation alloc]init];
        maaa.coordinate = (CLLocationCoordinate2D){poi.location.latitude, poi.location.longitude};
        maaa.title = poi.name;
        maaa.subtitle= poi.address;
        [_placeArray addObject:maaa];
        
        [annotations addObject:maaa];
    }
    [_tableview reloadData];
    
    [_mapView addAnnotations:annotations];
    [_mapView showAnnotations:annotations animated:YES];
    
}
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    if ([view.annotation.title isEqualToString:@"当前位置"]) {
        return;
    }
    
    _locationView.hidden = NO;
    _nameLabel.text = view.annotation.title;
    userClickPlace = view.annotation.title;
    _addressLabel.text = view.annotation.subtitle;
    searchCoordinate  = view.annotation.coordinate;
}
//点击地图气泡
- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view{
    NSLog(@"dianjiqipao");
    if ([view.annotation.title isEqualToString:@"当前位置"]) {
        return;
    }
    
    MAMapDetailViewController *vc= [[MAMapDetailViewController alloc]init];
    vc.cityStr = self.cityStr;
    vc.districtStr = userClickPlace;
    vc.myLocation = userNowCoordinate;
    vc.endLoc = view.annotation.coordinate;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
//单击地图底图调用此接口
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate{
    [self.view endEditing:YES];
    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0,0};
    pt = coordinate;
    
}
#pragma mark
#pragma mark  ------searbar
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (lastSearchString.length != 0 && [searchBar.text isEqualToString:@""]) {
        return NO;
    }else{
        return YES;
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (lastSearchString != nil && [searchText isEqualToString:@""]) {
        [_searchBar resignFirstResponder];
        
        [_placeArray removeAllObjects];
        
        NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
        [_mapView removeAnnotations:array];
        if (_locationView.hidden == NO) {
            _locationView.hidden = YES;
        }
        
        [_mapView setCenterCoordinate:userNowCoordinate];
        _tableview.alpha = 0;
        _tableview.hidden = YES;
        _mapView.zoomLevel = 17.1f;
        
        
    }else{
        
        [_placeArray removeAllObjects];
        if (![searchText isEqualToString:@""]) {
            

            
        }
    }
    lastSearchString = searchText;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [_placeArray removeAllObjects];
    
    [UIView animateWithDuration:0.25 animations:^{
        _tableview.frame = CGRectMake(0, _searchView.height, kScreenWidth, kScreenHeight - _searchView.height - 64);
        _tableview.hidden = NO;
        _tableview.alpha = 1;
    }];
    
    currentPage = 1;
    [self initDataWithSearch:_searchBar.text withPage:currentPage];
    
    NSLog(@"%@  %@ ",self.cityStr,_searchBar.text);
    [_searchBar resignFirstResponder];
    [_searchTF resignFirstResponder];
    
    
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    [_searchBar resignFirstResponder];
    
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_searchBar resignFirstResponder];
    [self.view endEditing:YES];
}

- (void)clickToGetSearch:(SQButton *)btn{
    
    [_searchBar resignFirstResponder];
    
    if (btn.isSelected == NO) {
        [UIView animateWithDuration:0.25 animations:^{
            _searchView.hidden = NO;
        }];
        btn.isSelected = YES;
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            _searchView.hidden = YES;
            _searchTF.text = @"";
        }];
        btn.isSelected = NO;
    }
    
}

// 拉开左侧:点击.
- (void)sideLeftButton_selector:(id)sender {
    
    NSLog(@"SubdistrictViewController...");
    [self.revealController toggleSidebar:!self.revealController.sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
